<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>18</title>
<script src="vue.js"></script>
  <style>
    table {
      border: 1px solid #e9e9e9;
      border-collapse: collapse;
      border-spacing: 0;
    }

    th,
    td {
      padding: 8px 16px;
      border: 1px solid #e9e9e9;
      text-align: left;
    }

    th {
      background-color: #f7f7f7;
      color: black;
      font-weight: 600;
    }
  </style>
</head>

<body>
  <div id="app">
    <div v-if="books.length">
      <table>
        <thread>
          <tr>
            <th>id</th>
            <th>商品名称</th>
            <th>商品价格</th>
            <th>商品数量</th>
            <th>操作</th>
          </tr>
        </thread>
        <tbody>
          <tr v-for="(book, index) in books" :key="book">
            <td>{{index+1}}</td>
            <td>{{book.name}}</td>
            <td>{{book.price | showPrice}}</td>
            <td>
              <button @click="decrease(index)" :disabled="book.count <= 0">-</button>
              {{book.count}}
              <button @click="increase(index)">+</button>
            </td>
            <td>
              <button @click="removeClick(index)">移除</button>
            </td>
          </tr>

        </tbody>

      </table>
      <h2>总价：{{totalPrice | showPrice}}</h2>
    </div>
    <h2 v-else>购物车为空</h2>
    商品名称<input type="text" v-model="name">
    商品价格<input type="text" v-model="price">
    <button @click="add">添加</button>
  </div>
  <script>
    const app = new Vue({
      el: "#app",
      data: {
        books: [

          { "name": "充电宝", "price": 10, "count": 1 },
          { "name": "小风扇", "price": 10, "count": 1 },
          { "name": "小音箱", "price": 10, "count": 1 },
          { "name": "蓝牙耳机", "price": 10, "count": 1 },
        ],
        name: "",
        price: ""

      },
      methods: {
        decrease(index) {
          this.books[index].count -= 1
        },
        increase(index) {
          this.books[index].count += 1
        },
        removeClick(index) {
          this.books.splice(index, 1)
        },

        add() {
          this.books.push({
            name: this.name, price: this.price, count: 1
          })
          this.name = ""
          this.price = ""
        }
      },
      computed: {
        totalPrice() {
          let totalPrice = 0
          for (let item of this.books) {
            totalPrice += item.price * item.count
          }
          return totalPrice
        }
      },
      filters: {
        showPrice(price) {
          return '￥' + (price * 1).toFixed(2)
        }
      }
    })
  </script>
</body>

</html>